# --*-- coding:utf-8 --*--

import warnings
warnings.filterwarnings("ignore")
import requests
import datetime
import time
import math
from selenium import webdriver
import re
import json
import string
import random
import os
import xlrd
import urllib
from bs4 import BeautifulSoup


def hostname():
	sys = os.name
	if sys == 'nt':
		hostname = os.getenv('computername')
		return hostname
	elif sys == 'posix':
		host = os.popen('echo $HOSTNAME')
		try:
			hostname = host.read()
			return hostname
		finally:
			host.close()
	else:
		return 'Unkwon hostname'


def taobaonick_to_cn(nickname):

	c = urllib.parse.unquote(nickname)
	zhPattern = re.compile(u'[\u4e00-\u9fa5]+')
	match = zhPattern.search(c)
	user_nick = ''
	if match:
		user_nick = c
	else:
		user_nick = c.encode('utf-8').decode('unicode_escape')
	return user_nick

def Yellow_data(cookies):

	#获取店铺名称

	url = 'https://zhaoshang.tmall.com/tmallwork/transSellerRemind.htm'

	head = {
		'Host': 'zhaoshang.tmall.com',
		'Connection': 'keep-alive',
		'Upgrade-Insecure-Requests': '1',
		'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
		'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
		'Accept-Encoding': 'gzip, deflate, br',
		'Accept-Language': 'zh-CN,zh;q=0.9'

	}
	data = {
		'market':'TMALL',
		'tmallcenter':'true',
		'spm':'687.8433302.40003.i1'
	}

	resp  = requests.get(url,headers = head,verify=False,params = data,cookies = cookies)
	soup = BeautifulSoup(resp.text)
	return soup.select('em')[2].text
	# try:
	# 	user_taobao = cookies["sn"]

	# except:
	# 	user_taobao = cookies["tracknick"]

	# storeName = str(taobaonick_to_cn(user_taobao)).split(':')[0]

	# # # # 获取店铺商品数量
	# driver = webdriver.PhantomJS()
	# driver.maximize_window()
	# driver.get('https://www.taobao.com/')  # 地址栏里输入网址
	# time.sleep(2)
	# cookies_dic = {}
	# cookies_list = driver.get_cookies()
	# for i in cookies_list:
	# 	cookies_dic[i["name"]] = i["value"]
	# driver.quit()

	# now_time = datetime.datetime.now().strftime("%Y%m%d")  #前一天

	# url = 'http://shopsearch.taobao.com/search'
	# data = {
	# 		'app':'shopsearch',
	# 		'q':storeName,
	# 		'js':'1',
	# 		'initiative_id':'staobaoz_'+str(now_time),
	# 		# 'initiative_id':'staobaoz_20180217',
	# 		'ie':'utf8'
	# }
	# data = {
	# 	# 'app':'shopsearch',
	# 	'ie':'utf8',
	# 	'initiative_id':'staobaoz_'+str(now_time),
	# 	'js':'1',
	# 	'q':storeName,
	# 	'suggest':'0_2',
	# 	'_input_charset':'utf-8',
	# 	'wq':storeName,
	# 	'suggest_query':storeName,
	# 	'source':'suggest'
	# }
	# head = {
	# 		'Host': 'shopsearch.taobao.com',
	# 		'Connection': 'keep-alive',
	# 		'Cache-Control': 'max-age=0',
	# 		'Upgrade-Insecure-Requests': '1',
	# 		'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
	# 		'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
	# 		'Accept-Encoding': 'gzip, deflate, br',
	# 		'Accept-Language': 'zh-CN,zh;q=0.9'

	# }
	# session = requests.Session()
	# resp = session.get(url,headers = head,verify=False,params = data,allow_redirects=False,cookies = cookies_dic)
	# url = resp.headers['Location']
	# print (url)
	# print (resp.text)

	# procnt = re.findall(r'"procnt":([^"]+),',resp.text)[0]
	# return procnt
	
def Blue_data(cookies):

	# excel 蓝色字体数据

	end_time = (str(datetime.datetime.now() - datetime.timedelta(days = 1)).split(' ')[0])
	start_time = (str(datetime.datetime.now() - datetime.timedelta(days = 30)).split(' ')[0])

	url = 'https://sycm.taobao.com/adm/v2/downloadBySchema.do?name=test-1&logicType=shop&dimId=1&themeId=1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10&startDate='+start_time+'&endDate='+end_time+'&isAutoUpdate=Y&deviceType=1%2C0%2C2&indexCode=597%2C117%2C5%2C198%2C279%2C288%2C225%2C207%2C333%2C189%2C383&dateType=day&reportType=1'
	head = {
			'Host': 'sycm.taobao.com',
			'Upgrade-Insecure-Requests': '1',
			'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
	resp = requests.get(url,headers = head,verify=False,stream=True,cookies = cookies)

	excel_name = ''.join(random.sample(string.ascii_letters + string.digits, 8)) + ".xls"
	with open(excel_name, 'wb') as fd:
		for chunk in resp.iter_content():
			fd.write(chunk)

	# #读取数据
	try:
		filename = xlrd.open_workbook(excel_name)
		sheet = filename.sheets()[0]
		nrows = sheet.nrows

		# 取出每行数据
		row_list=[]
		for i in range(8,nrows):
			row_datas = sheet.row_values(i)
			row_list.append(row_datas)
		if (hostname()) == 'DESKTOP-424AROC':  # 本地
			os.remove(excel_name)
		else:
			os.remove('/home/Django_Web/TaobaoWeb_Project/' + excel_name)  # 服务器
		return row_list

	except:
		return {"status":False, "result":[], "msg":"淘宝登陆过期"}

def Red_data(cookies):

	url = 'https://sycm.taobao.com/portal/coreIndex/getTableData.json'
	head = {
			'Host': 'sycm.taobao.com',
			'Connection': 'keep-alive',
			'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
			}

	start_time = (str(datetime.datetime.now() - datetime.timedelta(days = 1)).split(' ')[0])
	dateRange = str(start_time) + "|" + str(start_time)

	data = {
			'device':'0',
			'_':'1536653046185',
			'dateRange':dateRange,
			'token':'cd9f7d2e9',
			'dateType':'day',
			'indexCode':'payAmt,uv,payRate,payPct,rfdSucAmt,p4pExpendAmt,zzExpendAmt,tkExpendAmt,payByrCnt,payOldByrCnt,olderPayAmt,payOrdCnt,payItmCnt,cartByrCnt,cartCnt,cltItmCnt,pv'}

	resp = requests.get(url,headers = head,verify=False,params = data,cookies = cookies)

	try:
		resp.json()['code']
		return {"status":False, "result":[], "msg":"淘宝登陆过期"}
	except:
		if resp.json()['content']['code'] == 1003:  # 时间参数错误
			return {'status':False,'result':'时间参数错误','msg':'','code':1003}
		elif resp.json()['content']['code'] == 0:   # 正确返回数据
			cltItmCnt_list = []
			for i in resp.json()['content']['data']:
				cltItmCnt_list.append(i['cltItmCnt']['value'])
			return cltItmCnt_list

def Refund_rate(cookies):

	#退款率

	start_time = (str(datetime.datetime.now() - datetime.timedelta(days = 1)).split(' ')[0])
	dateRange = str(start_time) + "|" + str(start_time)
	# dateRange = '2018-10-27|2018-10-27'

	url = 'https://sycm.taobao.com/qos/claim/general/trend.json'

	head = {
			'Host': 'sycm.taobao.com',
			'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
			}

	data = {
		'dateType':'day',
		'dateRange':dateRange,
		'indexCode':'rfdEndTime,rfdSucRate,rfdDsptRate',
		'_':'1542185795466',
		'token':'d9db81017'
	}
	# data = {
	# 		'_':'1536654764527',
	# 		'dateRange':dateRange,
	# 		'token':'cb86fb742',
	# 		'dateType':'day',
	# 		'indexCode':'rfdSucRate,rfdEndRate,rfdAvgEndTime'
	# }
	resp = requests.get(url,headers = head,verify=False,params = data,cookies = cookies)
	if resp.json()['code'] == 0:
		return resp.json()['data']['rfdSucRate']
	elif resp.json()['code'] == 5924:
		return resp.json()
	elif resp.json()['code'] == 1003:  #请求参数非法 时间不对
		return {'status':False,'result':'时间参数错误','msg':'','code':1003}
	else:
		return {'status':False,'result':'未知错误','msg':''}


def store_main(cookies):

	store_day_anaysis = []
	try:
		store_product_cou = Yellow_data(cookies)
	except:
		return {"msg":"淘宝登陆过期"}
	store_fetching_number = Blue_data(cookies)
	try:
		if store_fetching_number['result'] == []:
			return store_fetching_number
	except:
		pass

	Item_cnt = Red_data(cookies)
	try:
		if Item_cnt['code'] ==1003:
			return Item_cnt
	except:
		pass

	Refund = Refund_rate(cookies)
	try:
		if Refund['code'] ==1003:
			return Refund
	except:
		try:
			if Refund['code'] == 5924:
				return Refund
		except:
			pass
	

	for k ,j,h in zip(store_fetching_number,Refund,Item_cnt):
		day_anaysis = {}
		day_anaysis['statDate'] = k[0] # 日期
		day_anaysis['payItemcun'] = float(k[1].replace(',',''))  # 支付商品数
		day_anaysis['browse_number'] = float(k[2].replace(',','')) #浏览量
		day_anaysis['visitors'] = float(k[3].replace(',',''))	#访客数
		day_anaysis['payment'] = float(k[4].replace(',',''))	#支付金额
		day_anaysis['paymentRate'] = float(k[5].strip('%'))/100.0	#支付转化率
		day_anaysis['Unit_price'] = float(k[6].replace(',',''))	#客单价
		day_anaysis['payment_Number'] = float(k[7].replace(',','')) #支付件数
		day_anaysis['buyers'] = float(k[8].replace(',',''))	#支付买家属
		day_anaysis['old_buyers'] = float(k[9].replace(',',''))	#支付老买家数
		day_anaysis['add_pay_number'] = float(k[10].replace(',','')) # 加购人数
		day_anaysis['successful_refund'] = float(k[11].replace(',','')) #成功退款金额
 
		# 商品数量
		day_anaysis['store_product_cou'] = int(store_product_cou)

		# 退款率
		day_anaysis['Refund'] = j 

		# 商品收藏人数
		day_anaysis['Item_cnt'] = h

		#加入store_day_anaysis
		store_day_anaysis.append(day_anaysis)

	return store_day_anaysis









if __name__ == '__main__':

	#小狮子cookeis 
	#cookies = {'uc3': 'id2=&nk2=&lg2=', 'cna': '5dbzE7zfsnwCAW/myrh+5F+Z', 'apush698b6ba7330b40cbf3b99f896fcd909d': '%7B%22ts%22%3A1536651350127%2C%22parentId%22%3A1536651345143%7D', 'uc1': 'cookie14=UoTfLQVSdWsjDQ%3D%3D&lng=zh_CN', '_tb_token_': '1634f11d86b5', 'cookie2': '1f0f8d4023eee691385152dcc73ec7be', 'x': '2235708395', 'skt': 'c1f300e6bf79a1cc', 'v': '0', 't': 'edc1543eb80bfe302a7ae63344675e8b', 'csg': '6eb4288f', 'sn': '%E5%B0%8F%E7%8B%AE%E5%AD%90%E7%8E%A9%E5%85%B7%E4%B8%93%E8%90%A5%E5%BA%97%3A%E6%8E%A8%E5%B9%BF04', 'isg': 'BOnpxCq6lo_HC6o7i8aPNYoO9JxDtt3ocqX3S4veZVAPUglk0wbtuNfAEHjkUXUg', 'tracknick': '', 'unb': '3199442953'}
	
	# 御果
	#过期
	# cookies = {"_nk_":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","unb":"3397628220","csg":"dec84b98","_cc_":"Vq8l%2BKCLiw%3D%3D","JSESSIONID":"DC22BA1DA8E5B39C8B6279F170EE5699","apushd2dce1c5dd89f161d480bff397a6184e":"%7B%22ts%22%3A1539394298717%2C%22parentId%22%3A1539394297713%7D","isg":"BE9PsPb8SIdnAUz7G2CnQbtP0upZdKOWCMdRvWFc677FMG8yaUQz5k2iNu6OU3sO","cookie1":"UNaOmjEdkzPF0d%2BKqRdPBjspDZcJ%2BrbnVjjQlzW63YA%3D","cookie2":"1768dd99992e5491ad095f5c75d723b0","_tb_token_":"b3eb3e5eb76d","skt":"69fcde81df1e0549","uc1":"cookie16=VT5L2FSpNgq6fDudInPRgavC%2BQ%3D%3D&tmb=1&cookie21=URm48syIZxx%2F&cookie15=V32FPkk%2Fw0dUvg%3D%3D&existShop=true&pas=0&cookie14=UoTfItN5AuK3%2BA%3D%3D&tag=8&lng=zh_CN","tg":"0","tracknick":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","v":"0","dnk":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","_l_g_":"Ug%3D%3D","cookie17":"UNN0nnQ5PzBj6g%3D%3D","t":"7d77b1d80133c864ca43c755aa2d824f","sg":"%E5%BA%9702","cna":"yT1EFFgLEWoCAcFwhT6Vrka3","lgc":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","existShop":"MTUzOTM5NDI5NA%3D%3D","mt":"np=","uc3":"vt3=F8dByRqgMsT8g%2B%2FKY%2Fo%3D&id2=UNN0nnQ5PzBj6g%3D%3D&nk2=sHmGuBnK6YrEuQ%3D%3D&lg2=V32FPkk%2Fw0dUvg%3D%3D"}
	
	# 未过期
	# cookies = {"existShop":"MTU0MTU3NTU4NQ%3D%3D","tg":"0","dnk":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","csg":"57fc2efb","isg":"BCoqhU1wBQdDLIlrd8T5xlMBd5nMm671lRDUrrTj1n0I58qhnCv-BXCVc517DCaN","uc1":"cookie16=U%2BGCWk%2F74Mx5tgzv3dWpnhjPaQ%3D%3D&tmb=1&cookie21=URm48syIZxx%2F&cookie15=V32FPkk%2Fw0dUvg%3D%3D&existShop=true&pas=0&cookie14=UoTYN4TTato%2BGA%3D%3D&tag=8&lng=zh_CN","cna":"15ZiFBhnImkCAcFwhT7OdcJz","v":"0","uc3":"vt3=F8dByR%2FL7xGIlDzu1GE%3D&id2=UNN0nnQ5PzBj6g%3D%3D&nk2=sHmGuBnK6YrEuQ%3D%3D&lg2=UtASsssmOIJ0bQ%3D%3D","_l_g_":"Ug%3D%3D","_tb_token_":"e39553e8b4673","mt":"np=","_nk_":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","t":"0a1b88b7e9dae0ed7715cf7d89c706d1","skt":"2e33d34d8533c5f9","sg":"%E5%BA%9702","_cc_":"U%2BGCWk%2F7og%3D%3D","lgc":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","tracknick":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","JSESSIONID":"15077121A5CDB929FEE266F38F08B09A","cookie2":"1f867145aa0ad5237b293f6e4f4af945","unb":"3397628220","cookie1":"UNaOmjEdkzPF0d%2BKqRdPBjspDZcJ%2BrbnVjjQlzW63YA%3D","cookie17":"UNN0nnQ5PzBj6g%3D%3D"}
	# 无权限账号 
	cookies = {"csg":"4c79b9b3","skt":"09dc56e8dfcc99d2","uc3":"id2=&nk2=&lg2=","tracknick":"","unb":"908215743","isg":"BIiIZ90SR0CfW6vEE_0Y8jPWVf-aMew7-5o2iEI51IP2HSiH6kG8yx6Pk3ttNqQT","_m_h5_tk_enc":"bcce939beb7fef864a2c7fe4b1c8188a","v":"0","apushec1d7e5dc5fed3af7ab4142eec55be0f":"%7B%22ts%22%3A1542185440396%2C%22parentId%22%3A1542185437392%7D","t":"90ad624cfcec3f9685dd4120e5fac003","_mw_us_time_":"1542185435421","sn":"%E5%B0%8F%E5%B0%8F%E6%AD%AAshop%3A%E8%A5%BF%E7%93%9C%E5%AD%90","thw":"cn","_m_h5_tk":"bb550d4b869a8ea2777e494de7245b5b_1542194078014","uc1":"cookie14=UoTYNO6OvgDkZg%3D%3D&lng=zh_CN","cna":"15ZiFBhnImkCAcFwhT7OdcJz","_tb_token_":"7eeb6ee76555e","x":"655668183","cookie2":"1e7152b84ceb00e3b29b050dc4e97361"}

	print (store_main(cookies))


	#excel 黄色色字体数据
	# print (Yellow_data(cookies))

	#excel 蓝色字体数据
	# Blue_data(cookies)

	#excel 红色字体数据
	# Red_data(cookies)

	#excel 退款率数据 (需要权限才能进入生意参谋服务页面，小狮子账号没权限)
	# Refund_rate(cookies)
